﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CrawlerCore;
using HtmlAgilityPack;

namespace WCrawlerLib.WebSession.IPBoard
{
    public class IpBoardForumSession : ForumSessionBase
    {
        public IpBoardForumSession()
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            ContentType = "multipart/form-data; boundary=" + boundary;
        }

        public override bool CheckLoginStatus()
        {
            bool loginStatus = false;
            string content = HtmlDoc.DocumentNode.InnerHtml.ToLower();
            string pattern = @"(thank you|successful(ly|) logged in|log out|" + ObjForum.Account.UserName + ")";

            Regex r = new Regex(pattern);
            MatchCollection m = r.Matches(content);

            //If count > 1 successfully log in
            if (m.Count >= 1)
            {
                loginStatus = true;
            }
            return loginStatus;
        }

        public override string InitLoginParams(string postParams, params string[] pars)
        {
            throw new NotImplementedException();
        }

        public override string InitEditPostParams(string postParams, params string[] pars)
        {
            throw new NotImplementedException();
        }

        public override string InitNewReplyParams(string postParams, params string[] pars)
        {
            throw new NotImplementedException();
        }

        public override string InitNewThreadParams(string postParams, params string[] pars)
        {
            //========================================================================
            //Init new thread params
            Dictionary<string, string> paramDict = new Dictionary<string, string>();
            paramDict.Add("TopicTitle", pars[0]);
            paramDict.Add("TopicDesc", pars[0]);
            paramDict.Add("poll_question", "");
            paramDict.Add("ed-0_wysiwyg_used", "0");
            paramDict.Add("editor_ids[]", "ed-0");
            paramDict.Add("Post", pars[1].Replace("&", "%26"));
            paramDict.Add("enableemo", "yes");
            paramDict.Add("enablesig", "yes");
            paramDict.Add("iconid", pars[3]);
            paramDict.Add("st", HtmlDoc.GetValueInInputTag("hidden", "name", "st"));
            paramDict.Add("app", HtmlDoc.GetValueInInputTag("hidden", "name", "app"));
            paramDict.Add("module", HtmlDoc.GetValueInInputTag("hidden", "name", "module"));
            paramDict.Add("section", HtmlDoc.GetValueInInputTag("hidden", "name", "section"));
            paramDict.Add("do", HtmlDoc.GetValueInInputTag("hidden", "name", "do"));
            paramDict.Add("s", HtmlDoc.GetValueInInputTag("hidden", "name", "s"));
            paramDict.Add("p", HtmlDoc.GetValueInInputTag("hidden", "name", "p"));
            paramDict.Add("t", HtmlDoc.GetValueInInputTag("hidden", "name", "t"));
            paramDict.Add("f", pars[2]); //fId
            paramDict.Add("parent_id", HtmlDoc.GetValueInInputTag("hidden", "name", "parent_id"));
            paramDict.Add("attach_post_key", HtmlDoc.GetValueInInputTag("hidden", "name", "attach_post_key"));
            paramDict.Add("auth_key", HtmlDoc.GetValueInInputTag("hidden", "name", "auth_key"));
            paramDict.Add("removeattachid", HtmlDoc.GetValueInInputTag("hidden", "name", "removeattachid"));
            paramDict.Add("dosubmit", HtmlDoc.GetValueInInputTag("submit", "name", "dosubmit"));

            string boundary = pars[4];// "---------------------------" + DateTime.Now.Ticks.ToString("x");
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (KeyValuePair<string, string> par in paramDict)
            {
                postParams += "\r\n--" + boundary + "\r\n";
                postParams += string.Format(formdataTemplate, par.Key, par.Value);
            }
            postParams += "\r\n--" + boundary + "--\r\n";
            return postParams;
        }

        public override void InitGeneralPostParams(string postParams, params string[] pars)
        {
            throw new NotImplementedException();
        }

        public override void PostNewThread(string subject, string message, string fId, string iconId, string tagList, string prefixId)
        {
            string newThreadUrl = ObjForum.NewThreadUrlPattern.Replace("§", "&sect").Replace("[fid]", fId.ToString());
            newThreadUrl = GeneralClass.GetFullUrl(ObjForum.ForumUrl, newThreadUrl);
            Get(newThreadUrl);

            //Get POST Params 
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            _postParams = InitNewThreadParams(ObjForum.NewThreadParams, subject, message, fId, iconId, boundary);

            string postNewThreadUrl = ObjForum.ForumUrl + "/index.php?";
            Post(postNewThreadUrl);
        }

        public override bool PostNewReply(string topicUrl, string newReplyUrl, string postParams, string message)
        {
            throw new NotImplementedException();
        }

        public override bool PostEdit(string forumUrl, string topicUrl, string postId, string editParams, string subject, string message, string updateReason, string icon)
        {
            throw new NotImplementedException();
        }

        public override int GetAccountId()
        {
            int userId = -1;
            string homeUrl = ObjForum.ForumUrl + "/" + "index.php?";
            HtmlDocument doc = Get(homeUrl);
            string pattern = @"ipb\.vars\[\'member_id\']\s*\t*=\sparseInt\(\s(?<userId>([0-9]+))\s\)\;";
            Regex r = new Regex(pattern);
            Match m = r.Match(doc.DocumentNode.InnerHtml);
            if (m.Success)
                userId = int.Parse(m.Result("${userId}"));
            return userId;
        }
    }
}
